from core.url import url_for_page_view_personal, url_for_page_view_post
from models import User, Post

def Head_default():
    return {
        "sort" : "",
        "role" : "",
        "time" : "",
        "user" :{
            "url":"",
            "name":""
        },
        "post" :{
            "url" : "",
            "title" : ""
        }
    }

def Head_uid(uid):
    user = User.get_by_id(uid)

    if not user:
        return Head_default()

    return {
        "role": user.role,
        "user": {
            "url": url_for_page_view_personal(uid),
            "name": user.username
        }
    }

def Head_pid(pid):
    post = Post.get_by_id(pid)
    user = User.get_by_id(post.uid)

    if not post or not user:
        return Head_default()

    return {
        "role": user.role,
        "time" :post.time.strftime("%Y-%m-%d %H:%M"),
        "sort" : post.sort,
        "user" :{
            "url" : url_for_page_view_personal(user.id),
            "name" : user.username
        } ,
        "post" :{
            "url" : url_for_page_view_post(post.id),
            "title" : post.title
        }
    }


def Heads_uid(uid):
    posts = Post.get_by_uid(uid)
    if not posts:
        return []

    results = []
    for post in posts:
        head_data = Head_pid(post.id)
        if "user" in head_data:
            del head_data["user"]
        results.append(head_data)

    return results

